package com.mark.tool.image;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Hashtable;

import sun.misc.BASE64Encoder;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.client.j2se.MatrixToImageWriter;

/**
 * @description 二维码生成工具类
 * @author  maliqiang
 * @since  2017年5月12日
 * @version 1.0
 */
public class QRCodeUtil implements Serializable {
    public static final int DEFAULT_SIZE = 100;
    private static final int DEFAULT_MARGIN = 0;
    private static final long serialVersionUID = 5863650074037559983L;

    /**
     * 生成包含文本内容的二维码
     * @param contents 文本内容
     * @param width 图片宽度
     * @param height 图片高度
     * @return img的base64编码串
     */
    public static String enCode(String contents,Integer width,Integer height) {
        //base64码返回图片头
        StringBuilder base64Code = new StringBuilder("<img src='data:image/jpg;base64,") ;

        width = width==null?DEFAULT_SIZE:width;
        height = height==null? DEFAULT_SIZE:height;
        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hints.put(EncodeHintType.MARGIN, DEFAULT_MARGIN);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        try {
            BitMatrix byteMatrix = new MultiFormatWriter().encode(new String(contents.getBytes("UTF-8"), "UTF-8"), BarcodeFormat.QR_CODE, width, height,hints);
            MatrixToImageWriter.writeToStream(byteMatrix, "png", bao);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        base64Code.append(Base64Code(bao.toByteArray()));
        base64Code.append("' />");
        return base64Code.toString();
    }

    /**
     * 将文件转换成base64字串
     * @param b
     * @return
     */
    public static String Base64Code(byte[] b) {
        BASE64Encoder encoder = new BASE64Encoder();
        StringBuilder pictureBuffer = new StringBuilder();
        pictureBuffer.append(encoder.encode(b));
        String codeBase64 = pictureBuffer.toString();
        return codeBase64;
    }

}  